//
//  Product_Specifications_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 11-04-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "Product_Specifications_iPad_ViewController.h"
#import "dao.h"
#import "classGenericCell.h"
#import "CustomCell.h"

@interface Product_Specifications_iPad_ViewController ()

@end

@implementation Product_Specifications_iPad_ViewController

@synthesize tableViewSearch;
@synthesize dataArraySearch = _dataArraySearch;
@synthesize json;
@synthesize jsonProducto;
@synthesize lblProductDescription, lblSKU;
@synthesize textViewHTML;
@synthesize imgViewProduct;
@synthesize textViewOverviewHTML;
@synthesize jsonOverview;
@synthesize lblMark;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)hideTabBar {
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds);
                         tabBar.frame = tabFrame;
                         content.frame = window.bounds;
                     }];
}

- (void)showTabBar {
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds) - CGRectGetHeight(tabBar.frame);
                         tabBar.frame = tabFrame;
                         
                         CGRect contentFrame = content.frame;
                         contentFrame.size.height -= tabFrame.size.height;
                     }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [_dataArraySearch count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
                                 reuseIdentifier:CellIdentifier];
    }
    
    classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];
    
    cell.lblTitleLabel.text = objCell.strTitleLabel;
    cell.lblSubtitleLabel.text = objCell.strSubtitleLabel;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //Alternando colores en celdas
    if ((indexPath.row % 2) == 0) {
        cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
    }
    else {
        cell.backgroundColor = [UIColor whiteColor];
    }
}

- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString
{
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
    if (range.location != NSNotFound) {
        NSMutableString *mutable = [NSMutableString stringWithString:inputString];
        while (range.location != NSNotFound) {
            [mutable deleteCharactersInRange:range];
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        return mutable;
    }
    return inputString;
}

-(void) getHtmlAttribute:(NSString *) strHtml{
    
    NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                              NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)};
    
    NSData* dataUTF8 = [strHtml dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableAttributedString *stringWithHTMLAttributes = [[NSMutableAttributedString alloc] initWithData:dataUTF8 options:options documentAttributes:nil error:nil];
    
    [textViewHTML setAttributedText:stringWithHTMLAttributes];
}

-(void) getProductInfo:(int) intIdProducto{
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonDetalleProducto.aspx?strJsonBase=JsonDetalleProducto&strIdProducto=%i", intIdProducto];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load producto perfecto!!!");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"idp":"7", "dp":"Alicate universal 8” 84023. ", "dcom":"Alicate universal 8” electricista 84023 negro. ", "sku":"120813 ", "nr":"0", "nv":"0", "pn":"1900", "po":"600", "dcto":"70", "tof":"0", "idm":"4", "dmp":"Stanley", "img":"7/276_1.jpg", "min":"1", "max":"20" }]
             
             jsonProducto = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             for (int i = 0; i<jsonProducto.count; i++)
             {
                 lblMark.text = [[jsonProducto objectAtIndex:i] objectForKey:@"dmp"];
                 lblProductDescription.text = [[jsonProducto objectAtIndex:i] objectForKey:@"dcom"];
                 lblSKU.text = [[jsonProducto objectAtIndex:i] objectForKey:@"sku"];
             }
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
}

-(void) getHtmlOverviewAttribute:(NSString *) strHtml{
    
    NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                              NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)};
    
    NSData* dataUTF8 = [strHtml dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableAttributedString *stringWithHTMLAttributes = [[NSMutableAttributedString alloc] initWithData:dataUTF8 options:options documentAttributes:nil error:nil];
    
    [textViewOverviewHTML setAttributedText:stringWithHTMLAttributes];
}

- (void) retrieveOverviewHTML{
    
    //****************************************
    dao *objDAO = [[dao alloc] init];
    
    int intIdProducto = 0;
    intIdProducto = [objDAO obtainCurrentProduct];
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonDetalleProducto.aspx?strJsonBase=JsonOverviewProductoHtml&strIdProducto=%i", intIdProducto];
    
    NSLog(@"strUrl =%@", strUrl);
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load Attribute perfecto!!!");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"html":"<table>"}]
             
             jsonOverview = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             for (int i = 0; i<jsonOverview.count; i++)
             {
                 NSString *strHtml = [[jsonOverview objectAtIndex:i] objectForKey:@"html"];
                 
                 [self getHtmlOverviewAttribute:strHtml];
             }
             
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
    //****************************************
}

- (void) retrieveDataSearch{
    
    [_dataArraySearch removeAllObjects];
    _dataArraySearch = [[NSMutableArray alloc] init];
    
    self.tableViewSearch.hidden = NO;

    //****************************************
    dao *objDAO = [[dao alloc] init];
    
    int intIdProducto = 0;
    intIdProducto = [objDAO obtainCurrentProduct];
    
    //---------------------------------------------------------------------------------------------------
    //Leemos
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    //1.- Imagen normal
    NSString *strNameImageTmp = @"";
    NSString *documentsDirectory = [paths objectAtIndex:0];
    strNameImageTmp = [NSString stringWithFormat:@"3_%i.jpg", intIdProducto];
    
    NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    //-----------------------------------------------------------------------------------
    
    [imgViewProduct setImage:image]; //Asignamos la imagen

    //---------------------------------------------------------------------------------------------------
    
    [self retrieveOverviewHTML];
    
    [self getProductInfo:intIdProducto];
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonDetalleProducto.aspx?strJsonBase=JsonFichaProductoHtml&strIdProducto=%i", intIdProducto];
    
    NSLog(@"strUrl =%@", strUrl);
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load Attribute perfecto!!!");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"html":"<table>"}]
             
             json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             for (int i = 0; i<json.count; i++)
             {
                 NSString *strHtml = [[json objectAtIndex:i] objectForKey:@"html"];
                 
                 [self getHtmlAttribute:strHtml];
             }
             
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self retrieveDataSearch];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (IBAction)backToProduct:(id)sender {
    
    dao *objDAO = [[dao alloc] init];
    
    if ([objDAO obtainProductBack] == 0) {
        //Back desde el home
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
    }else{
        //Back desde la busqueda
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2] animated:YES];
    }
    
}
@end
